package com.rshang.rsdp.service.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.rshang.rsdp.annotation.Log;
import com.rshang.rsdp.bean.DataGrid;
import com.rshang.rsdp.bean.Response;
import com.rshang.rsdp.common.status.ExcelStatusCode;
import com.rshang.rsdp.common.status.GsStatusCode;
import com.rshang.rsdp.common.status.RyStatusCode;
import com.rshang.rsdp.common.status.StatusCode;
import com.rshang.rsdp.common.status.XgsStatusCode;
import com.rshang.rsdp.entity.DmRsdlGsa;
import com.rshang.rsdp.entity.DmRsdlGsb;
import com.rshang.rsdp.exception.RsdpSystemException;
import com.rshang.rsdp.kit.StrKits;
import com.rshang.rsdp.mapper.DmRsdlGsaMapper;
import com.rshang.rsdp.mapper.DmRsdlGsbMapper;
import com.rshang.rsdp.service.IDmRsdlGsbService;
import com.rshang.rsdp.service.IExcelService;
import com.rshang.rsdp.util.excel.CellKey;
import com.rshang.rsdp.util.i18n.I18nMessage;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 小公司代码表 服务实现类
 * </p>
 *
 * @author zhangjun
 * @since 2017-08-20
 */
@Service
public class DmRsdlGsbServiceImpl extends ServiceImpl<DmRsdlGsbMapper, DmRsdlGsb> implements IDmRsdlGsbService {

    private static final Logger logger = LoggerFactory.getLogger(DmRsdlGsbServiceImpl.class);

    @Autowired
    I18nMessage i18n;

    @Autowired
    DmRsdlGsaMapper gsMapper;

    @Autowired
    IExcelService excel;

    private static final List<CellKey> COLUMN_IMPORT = new ArrayList<CellKey>() {{
        add(new CellKey("公司", "1", 100, true));//1字符型 2数字型 3日期型 4日期时间 9其他
        add(new CellKey("小公司名称", "1", 100, true));
        add(new CellKey("小公司简称", "1", 50, false));
        add(new CellKey("计算方式", "1", 1, true));
    }};

    @Override
    public DataGrid getXgsPageList(Page<HashMap> page, HttpServletRequest request) {
        page.setRecords(this.baseMapper.getXgsPageList(page, StrKits.emptyToStr(request.getParameter("gs")), StrKits.emptyToStr(request.getParameter("xgs"))));
        return new DataGrid(page.getRecords(), page.getTotal());
    }

    @Log(module = "小公司列表", desc = "新增小公司")
    @Override
    public Response addSave(HttpServletRequest request, String czr) {
        if (this.baseMapper.selectCount(Condition.create().setSqlSelect("GSB_ID")
                .eq("GSB_MC", StrKits.emptyToStr(request.getParameter("gsbmc")))
                .eq("GS_ID", StrKits.emptyToStr(request.getParameter("sel_gs")))) > 0) {
            throw new RsdpSystemException(XgsStatusCode.XGS_FOUND.getCode(), i18n.getMessage(XgsStatusCode.XGS_FOUND.getKey()));
        } else {
            DmRsdlGsb gs = new DmRsdlGsb();
            gs.setGsbId(StrKits.uuid());
            gs.setGsId(StrKits.emptyToStr(request.getParameter("sel_gs")));
            gs.setGsbMc(StrKits.emptyToStr(request.getParameter("gsbmc")));
            gs.setGsbJc(StrKits.emptyToStr(request.getParameter("gsbjc")));
            gs.setJsfs(StrKits.emptyToStr(request.getParameter("sel_jsfs")));
            gs.setLrr(czr);
            gs.setXgr(czr);
            gs.setYxBz(StrKits.emptyToStr(request.getParameter("sel_yxbz")));
            gs.setXyBz(StrKits.emptyToStr(request.getParameter("sel_xybz")));
            if (this.baseMapper.insert(gs) > 0) {
                return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
            } else {
                return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
            }
        }
    }

    @Override
    public DmRsdlGsb get(HttpServletRequest request) {
        DmRsdlGsb result = this.selectById(StrKits.emptyToStr(request.getParameter("id")));
        if (result == null) {
            throw new RsdpSystemException(XgsStatusCode.XGS_NOTFOUND.getCode(), i18n.getMessage(XgsStatusCode.XGS_NOTFOUND.getKey()));
        } else {
            return result;
        }
    }

    @Log(module = "小公司列表", desc = "小公司编辑")
    @Override
    public Response editSave(HttpServletRequest request, String czr) {
        if (this.baseMapper.selectCount(Condition.create().setSqlSelect("GSB_ID")
                .eq("GSB_MC", StrKits.emptyToStr(request.getParameter("gsbmc")))
                .eq("GS_ID", StrKits.emptyToStr(request.getParameter("sel_gs")))
                .ne("GSB_ID", StrKits.emptyToStr(request.getParameter("hid_id")))) > 0) {
            throw new RsdpSystemException(XgsStatusCode.XGS_FOUND.getCode(), i18n.getMessage(XgsStatusCode.XGS_FOUND.getKey()));
        } else {
            DmRsdlGsb gs = new DmRsdlGsb();
            gs.setGsbId(StrKits.emptyToStr(request.getParameter("hid_id")));
            gs.setGsId(StrKits.emptyToStr(request.getParameter("sel_gs")));
            gs.setGsbMc(StrKits.emptyToStr(request.getParameter("gsbmc")));
            gs.setGsbJc(StrKits.emptyToStr(request.getParameter("gsbjc")));
            gs.setJsfs(StrKits.emptyToStr(request.getParameter("sel_jsfs")));
            gs.setXgr(czr);
            gs.setXgsj(new Date());
            gs.setYxBz(StrKits.emptyToStr(request.getParameter("sel_yxbz")));
            gs.setXyBz(StrKits.emptyToStr(request.getParameter("sel_xybz")));
            if (this.baseMapper.updateById(gs) > 0) {
                return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
            } else {
                return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
            }
        }
    }

    @Log(module = "小公司列表", desc = "小公司删除")
    @Override
    public Response deleteSave(HttpServletRequest request, String czr) {
        String ids = StrKits.emptyToStr(request.getParameter("id"));
        List<String> idList = Lists.newArrayList(ids.split(","));
        if (this.baseMapper.deleteBatchIds(idList) == idList.size()) {
            return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
        } else {
            throw new RsdpSystemException(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
        }
    }

    @Override
    public Response checkXgsmc(HttpServletRequest request) {
        String id = StrKits.emptyToStr(request.getParameter("id"));
        Wrapper wrapper = Condition.create().setSqlSelect("GSB_ID")
                .eq("GSB_MC", StrKits.emptyToStr(request.getParameter("xgsmc")))
                .eq("GS_ID", StrKits.emptyToStr(request.getParameter("gsid")));

        if (!"".equals(id)) {
            wrapper = wrapper.ne("GSB_ID", id);
        }
        if (this.baseMapper.selectCount(wrapper) > 0) {
            throw new RsdpSystemException(XgsStatusCode.XGS_FOUND.getCode(), i18n.getMessage(XgsStatusCode.XGS_FOUND.getKey()));
        }
        return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
    }


    @Override
    @Transactional
    @Log(module = "小公司列表", desc = "模板导入")
    public Response importSave(MultipartFile file, String czr) {
        if (file == null)//文件为空
        {
            throw new RsdpSystemException(ExcelStatusCode.XLS_EMPTY.getCode(), i18n.getMessage(ExcelStatusCode.XLS_EMPTY.getKey()));
        }
        InputStream is = null;
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        Cell cell0 = null;
        Cell cell1 = null;
        Cell cell2 = null;
        Cell cell3 = null;
        List<Row> data = new ArrayList<Row>();
        List<String> errList = new ArrayList<String>();
        DmRsdlGsa gs = null;
        DmRsdlGsb xgs = null;
        try {
            is = file.getInputStream();
            wb = new HSSFWorkbook(is);

            if (wb.getNumberOfSheets() == 0)//模板必须要有一个sheet表
            {
                throw new RsdpSystemException(ExcelStatusCode.XLS_NOTFORMATED.getCode(), i18n.getMessage(ExcelStatusCode.XLS_NOTFORMATED.getKey()));
            }
            //读取excel文件
            sheet = wb.getSheetAt(0);//读取第一个sheet表
            int rowCount = sheet.getPhysicalNumberOfRows();//获取模板总数
            logger.debug("xgs importSave row count:{}", rowCount);
            if (rowCount < 2)//空数据
            {
                throw new RsdpSystemException(ExcelStatusCode.XLS_DATAEMPTY.getCode(), i18n.getMessage(ExcelStatusCode.XLS_DATAEMPTY.getKey()));
            }
            //循环读取数据
            Iterator<Row> it = sheet.iterator();
            int rowNo = 0;
            CellKey cellKey;
            //循环读取数据
            while (it.hasNext()) {
                row = it.next();
                if (row != null && row.getRowNum() > 0) {
                    rowNo = row.getRowNum();
                    //logger.debug("xgs importSave row:{}-{}-{}",cell0,cell1,cell2);
                    //模板校验
                    for (int i = 0; i < 4; i++) {
                        excel.setStringCell(row.getCell(i));
                        cellKey = COLUMN_IMPORT.get(i);
                        excel.checkCellValue(rowNo, i, cellKey, row.getCell(i), errList);
                        if(i==3) {
                        	if (row.getCell(i) != null && StringUtils.isNotEmpty(row.getCell(i).getStringCellValue())) {
                                if(!"0".equals(row.getCell(i).getStringCellValue())&&!"1".equals(row.getCell(i).getStringCellValue())) {
                                		errList.add(i18n.getMessage(GsStatusCode.XGS_JSFS.getKey(), new Object[]{(rowNo+1)+"", i + 1, cellKey.getHead()}));
                                }
                            }
                        }
                    }

                    if (errList.size() > 0) {
                        if (!data.isEmpty()) {
                            data.clear();
                        }
                    } else {
                        data.add(row);
                    }
                }
            }

        } catch (IOException e) {
            logger.error("xgs importSave error:{}", e.getMessage());
            throw new RsdpSystemException(StatusCode.SERVER_ERROR.getCode(), e.getMessage());
        } finally {
            try {
                //关闭流及文件
                wb.close();
                is.close();
            } catch (IOException e) {
                logger.error("xgs importSave close error:{}", e.getMessage());
            }
        }
        if (errList.size() > 0)//模板校验错误直接抛出
        {
            return new Response(ExcelStatusCode.XLS_ERROR.getCode(), i18n.getMessage(ExcelStatusCode.XLS_ERROR.getKey(), new Object[]{Joiner.on("").join(errList)}));
        } else {
            String plId = StrKits.uuid();
            Map gsMap = new HashMap();
            List<DmRsdlGsa> gsList = gsMapper.selectList(Condition.create());//获取所有公司
            for (DmRsdlGsa gst : gsList) {
                gsMap.put(gst.getGsMc(), gst.getGsId());
            }
            //logger.debug("xgs importSave gsMap:{}", gsMap);
            Map xgsMap = new HashMap();
            List<DmRsdlGsb> xgsList = baseMapper.selectList(Condition.create());//获取所有小公司
            for (DmRsdlGsb xgst : xgsList) {
                xgsMap.put(xgst.getGsId() + xgst.getGsbMc(), xgst.getGsbId());
            }
            //logger.debug("xgs importSave xgsMap:{}", xgsMap);
            //获取公司所有数据
            for (Row rt : data) {
                cell0 = rt.getCell(0);//公司
                cell1 = rt.getCell(1);//小公司全称
                cell2 = rt.getCell(2);//小公司简称
                cell3 = rt.getCell(3);//计算方式
                //logger.debug("xgs importSave success row:{}-{}-{}",cell0,cell1,cell2);
                //logger.debug("xgs importSave condition1:{}",gsMap.containsKey(cell0.getStringCellValue())&&!xgsMap.containsKey(String.valueOf(gsMap.get(cell0.getStringCellValue()))+cell1.getStringCellValue()));
                //公司存在 小公司不存在  新建小公司
                if (gsMap.containsKey(cell0.getStringCellValue()) && !xgsMap.containsKey(String.valueOf(gsMap.get(cell0.getStringCellValue())) + cell1.getStringCellValue())) {
                    xgs = new DmRsdlGsb();
                    xgs.setGsbId(StrKits.uuid());
                    xgs.setGsId(String.valueOf(gsMap.get(cell0.getStringCellValue())));
                    xgs.setGsbMc(cell1.getStringCellValue());
                    xgs.setGsbJc((cell2 == null || StringUtils.isEmpty(cell2.getStringCellValue())) ? cell1.getStringCellValue() : cell2.getStringCellValue());
                    xgs.setJsfs(cell3.getStringCellValue());
                    xgs.setLrr(czr);
                    xgs.setXgr(czr);
                    xgs.setPlBs(plId);
                    if (this.baseMapper.insert(xgs) < 0) {
                        return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
                    }
                    xgsMap.put(xgs.getGsId() + xgs.getGsbMc(), xgs.getGsbId());
                }
                //logger.debug("xgs importSave condition2:{}",!gsMap.containsKey(cell0.getStringCellValue())&&!xgsMap.containsKey(String.valueOf(gsMap.get(cell0.getStringCellValue()))+cell1.getStringCellValue()));
                //公司不存在 小公司不存在 新建公司 小公司
                if (!gsMap.containsKey(cell0.getStringCellValue()) && !xgsMap.containsKey(String.valueOf(gsMap.get(cell0.getStringCellValue())) + cell1.getStringCellValue())) {
                    //公司
                    gs = new DmRsdlGsa();
                    gs.setGsId(StrKits.uuid());
                    gs.setGsMc(cell0.getStringCellValue());
                    gs.setLrr(czr);
                    gs.setXgr(czr);
                    gs.setPlBs(plId);

                    //小公司
                    xgs = new DmRsdlGsb();
                    xgs.setGsbId(StrKits.uuid());
                    xgs.setGsId(gs.getGsId());
                    xgs.setGsbMc(cell1.getStringCellValue());
                    xgs.setGsbJc((cell2 == null || StringUtils.isEmpty(cell2.getStringCellValue())) ? cell1.getStringCellValue() : cell2.getStringCellValue());
                    xgs.setJsfs(cell3.getStringCellValue());
                    xgs.setLrr(czr);
                    xgs.setXgr(czr);
                    xgs.setPlBs(plId);
                    if (gsMapper.insert(gs) < 0 || this.baseMapper.insert(xgs) < 0) {
                        return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
                    }
                    gsMap.put(gs.getGsMc(), gs.getGsId());
                    xgsMap.put(xgs.getGsId() + xgs.getGsbMc(), xgs.getGsbId());
                }
            }
        }

        return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
    }


    @Override
    public List<HashMap> getXgsByCzr(HttpServletRequest request, String czr) {
        return this.baseMapper.getXgsByCzrGs(czr, StrKits.emptyToStr(request.getParameter("gsid")));
    }

    @Override
    public List<DmRsdlGsb> getYxXgsByGs(HttpServletRequest request) {
        return this.baseMapper.selectList(Condition.create()
                .eq("YX_BZ", "1")
                .eq("XY_BZ", "1")
                .eq("GS_ID", StrKits.emptyToStr(request.getParameter("gsid")))
                .orderBy("XGSJ", false)
        );
    }

	@Override
	public Response checkXgsmc2(HttpServletRequest request) {
		DmRsdlGsa gsa = new DmRsdlGsa();
		gsa.setGsMc(StrKits.emptyToStr(request.getParameter("gsamc")));
		gsa = gsMapper.selectOne(gsa);
		
		if(gsa==null||gsa.getGsId()==null||"".equals(gsa.getGsId()))
		{
			return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
		}
		else
		{
			Wrapper wrapper = Condition.create().setSqlSelect("GSB_ID")
	                .eq("GSB_MC", StrKits.emptyToStr(request.getParameter("gsbmc")))
	                .eq("GS_ID", gsa.getGsId());

	        if (this.baseMapper.selectCount(wrapper) > 0) {
	            throw new RsdpSystemException(XgsStatusCode.XGS_FOUND.getCode(), i18n.getMessage(XgsStatusCode.XGS_FOUND.getKey()));
	        }
	        return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
		}
        
	}

	@Override
	public Response gsAddSave(HttpServletRequest request, String czr) {
		DmRsdlGsa gsa = new DmRsdlGsa();
		gsa.setGsMc(StrKits.emptyToStr(request.getParameter("gsamc")));
		gsa = gsMapper.selectOne(gsa);
		
		if(gsa==null||gsa.getGsId()==null||"".equals(gsa.getGsId()))
		{
			gsa = new DmRsdlGsa();
			gsa.setGsId(StrKits.uuid());
			gsa.setGsMc(StrKits.emptyToStr(request.getParameter("gsamc")));
			gsa.setLrr(czr);
			gsa.setXgr(czr);
			gsa.setYxBz("1");
			gsa.setXyBz("1");
            if (this.gsMapper.insert(gsa) <= 0) {
            		return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
            }
		}
		
		if (this.baseMapper.selectCount(Condition.create().setSqlSelect("GSB_ID")
                .eq("GSB_MC", StrKits.emptyToStr(request.getParameter("gsbmc")))
                .eq("GS_ID", gsa.getGsId())) > 0) {
            throw new RsdpSystemException(XgsStatusCode.XGS_FOUND.getCode(), i18n.getMessage(XgsStatusCode.XGS_FOUND.getKey()));
        } else {
            DmRsdlGsb gs = new DmRsdlGsb();
            gs.setGsbId(StrKits.uuid());
            gs.setGsId(gsa.getGsId());
            gs.setGsbMc(StrKits.emptyToStr(request.getParameter("gsbmc")));
            gs.setGsbJc(StrKits.emptyToStr(request.getParameter("gsbmc")));
            gs.setJsfs(StrKits.emptyToStr(request.getParameter("sel_jsfs")));
            gs.setLrr(czr);
            gs.setXgr(czr);
            gs.setYxBz("1");
            gs.setXyBz("1");
            if (this.baseMapper.insert(gs) > 0) {
                return new Response(StatusCode.SUCCESS.getCode(), i18n.getMessage(StatusCode.SUCCESS.getKey()));
            } else {
                return new Response(StatusCode.OPER_FAILED.getCode(), i18n.getMessage(StatusCode.OPER_FAILED.getKey()));
            }
        }
	}
}

